package com.moonciki.artadmin.core.tools;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 岳仕奇
 * @description: TODO
 * @date 2021/11/2 14:11
 */
@Slf4j
public class GlobalThreadCounter {

    public volatile static Map<String, AtomicInteger> counterMap = new ConcurrentHashMap<>();

    /**
     * 增数量
     * @param key
     * @return
     */
    public static int add(String key){

        AtomicInteger consumerCount = counterMap.get(key);
        if(consumerCount == null){
            synchronized (GlobalThreadCounter.class){
                consumerCount = counterMap.get(key);
                if(consumerCount == null){
                    consumerCount = new AtomicInteger(0);
                    counterMap.put(key, consumerCount);
                }
            }
        }

        int count = consumerCount.addAndGet(1);

        log.info("add_thread_count : " + count);

        return count;
    }

    /**
     * 减数量
     * @param key
     * @return
     */
    public static int remove(String key){

        AtomicInteger consumerCount = counterMap.get(key);
        if(consumerCount == null){
            return 0;
        }

        int count = consumerCount.addAndGet(-1);

        log.info("remove_thread_count : " + count);
        return count;
    }


    public static void main(String[] args) {

        add("test");

        remove("test");

        System.out.println("ending ");
    }

}
